<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form'
import type { VxeTableGridOptions } from '#/adapter/vxe-table'
import { computed, h, ref, onBeforeMount, markRaw } from 'vue'
import { Page, useVbenModal, prompt,Tippy,confirm } from '@vben/common-ui'
import { Button, message, Tag, Space, Radio, Input, Select, SelectOption, DatePicker, Cascader, Spin, Row } from 'ant-design-vue'
import { useVbenVxeGrid } from '#/adapter/vxe-table'
import {
  getPurchaseIndex,
  getPurchaseIndex2,
  getPurchaseSum,
  getPurchaseSum2,
  savePurchaseProgress,
  saveProgressColumn,
  getWarehouseOptions,
  getGoodsHeelMan,
  getMerchandiserDict,
  exportPurchaseProgress,
  exportPurchaseProgress2,
  signFinish,
} from '#/api/materialPurchaseProgress'
import { useDebounceFn } from '@vueuse/core'
import SendGoodsSkuModalComponent from './modules/sendGoodsSkuModal.vue'
import Again from './modules/againModal.vue'
import SearchTemplate from '../modules/searchTemplate.vue'
import { saveSearchTemplate, getSupplyList,getFactoryList,getAdminList } from '#/api/common'
import { getCategoryOptions, getTimeCategoryOptions } from '#/api/materialBatchBill'
import { doMaterialCategory } from '#/api/material'
import TwoFields from '../modules/two-fields.vue';

import { copyToClipboard } from '@vben/utils'
import SearchTemplateSelect from './components/SearchTemplateSelect.vue'

interface RowType {
  [key: string]: any
}

const header_data = ref<any>([])
const field_data = ref<any>([])
const header_info = ref<any>([])
const selectedRows = ref<any>([])
const formData = ref<any>({})
const footerData = ref<any>([])
const keyword = ref({
  supply_id: '',
  warehouse_id: '',
  heel_man_name: '',
  merchandiser: '',
  material_type: '',
  admin_id: '',
})

const dataType = ref('1') // 1:实时取数 2:快照取数

// 初始化时获取商品分类和时间分类选项
onBeforeMount(() => {
  fetchCategoryOptions()
  fetchTimeCategoryOptions()
})

// 获取商品分类选项
const fetchCategoryOptions = async () => {
  try {
    const { list } = await getCategoryOptions()
    // 动态更新formApi中的category选项
    if (gridApi && gridApi.formApi) {
      gridApi.formApi.updateSchema([
        {
          componentProps: {
            options: list || [],
          },
          fieldName: 'category',
        },
      ])
    }
  } catch (error) {
    console.error('获取商品分类选项失败:', error)
    return []
  }
}

// 获取时间分类选项
const fetchTimeCategoryOptions = async () => {
  try {
    const { list } = await getTimeCategoryOptions()
    // 动态更新formApi中的time_category选项
    if (gridApi && gridApi.formApi) {
      gridApi.formApi.updateSchema([
        {
          componentProps: {
            options: list || [],
          },
          fieldName: 'time_category',
        },
      ])
    }
  } catch (error) {
    console.error('获取时间分类选项失败:', error)
    return []
  }
}

const fetchSupplyOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getSupplyList({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'id',
    initValue: !keyword ? formData.value?.supply_id : '',
    select: true,
  })

  return list.map((item: any) => ({
    label: item.SupplyNa,
    value: item.id,
  }))
}

const fetchWarehouseOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getFactoryList({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'id',
    initValue: !keyword ? formData.value?.warehouse_id : '',
    select: true,
  })

  return list.map((item: any) => ({
    label: item.SupplyNa,
    value: item.id,
  }))
}

const fetchHeelManOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getAdminList({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'heel_man_name',
    initValue: !keyword ? formData.value?.heel_man_name : '',
    select: true,
    is_caigou:true
  })

  return list.map((item: any) => ({
    label: item.realname,
    value: item.id,
  }))
}

const fetchAdminOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getAdminList({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'id',
    initValue: !keyword ? formData.value?.admin_id : '',
    select: true,
    group_id:7,
    is_caigou:true
  })

  return list.map((item: any) => ({
    label: item.realname,
    value: item.id,
  }))
}

const fetchMerchandiserOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await getMerchandiserDict({
    quick_search: keyword,
    page: 1,
    limit: 1000,
    key: 'merchUsers',
    initKey: 'data_value',
    initValue: !keyword ? formData.value?.merchandiser : '',
    select: true,
  })

  return list.map((item: any) => ({
    label: item.data_value,
    value: item.data_value,
  }))
}

const fetchMaterialCategoryOptions = async ({ keyword = '' }: Record<string, any>) => {
  const { list } = await doMaterialCategory({
    quick_search: keyword,
    page: 1,
    limit: 30,
    initKey: 'id',
    initValue: !keyword ? formData.value?.material_type : '',
    select: true,
  })

  return list.map((item: any) => ({
    label: item.name,
    value: item.id,
  }))
}

// 获取选中行的ID数组
const getSelectionIds = () => {
  return selectedRows.value.map((row: any) => row.id)
}

// 表单配置
const formOptions: VbenFormProps = {
  wrapperClass: 'grid-cols-5',
  schema: [
    {
      component: 'Cascader',
      fieldName: 'category',
      label: '货品分类',
      operator: '123',
      componentProps: {
        options: [],
        allowClear: true,
        multiple: true,
        showSearch: true,
        alwaysLoad: true,
        showCheckedStrategy: Cascader.SHOW_CHILD,
        maxTagCount: 'responsive',
      },
    },
    {
      component: 'Select',
      fieldName: 'a*type',
      label: '季节',
      operator: 'IN',
      componentProps: {
        options: [
          { label: '春', value: '1' },
          { label: '夏', value: '2' },
          { label: '秋', value: '3' },
          { label: '冬', value: '4' },
          { label: '通用', value: '5' },
        ],
        allowClear: true,
        mode: 'multiple',
        maxTagCount: 'responsive',
        placeholder: '请选择季节',
      },
    },
    {
      component: 'DatePicker',
      fieldName: 'a*year',
      label: '年份',
      operator: '=',
      render: 'customRender',
      componentProps: {
        picker: 'year',
        valueFormat: 'YYYY',
      },
    },
    {
      component: 'Input',
      fieldName: 'a*purchase_sn',
      label: '手工单号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
        placeholder: '请输入手工单号',
      },
    },
    {
      component: 'Input',
      fieldName: 'a*caigou_id',
      label: '采购单号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
        placeholder: '请输入采购单号',
      },
    },
    {
      component: 'Input',
      fieldName: 'b*template_no',
      label: '简码',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
        placeholder: '请输入简码',
      },
    },
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchSupplyOptions,
          filterOption: false,
          onSearch: useDebounceFn((value: string) => {
            keyword.value.supply_id = value
          }, 300),
          params: {
            keyword: keyword.value.supply_id || undefined,
          },
          showSearch: true,
          immediate: false,
          alwaysLoad: true,
          allowClear: true,
          mode: 'multiple',
          maxTagCount: 'responsive',
          visibleEvent: 'onFocus',
          onDropdownVisibleChange: (open: boolean) => {
            keyword.value.supply_id = ''
          },
        }
      },
      fieldName: 'a*supply_id',
      label: '供应商',
      operator: 'IN',
    },
    // 新增：生产工厂
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchWarehouseOptions, // 复用仓库选项，实际应该是工厂
          filterOption: false,
          onSearch: useDebounceFn((value: string) => {
            keyword.value.warehouse_id = value
          }, 300),
          params: {
            keyword: keyword.value.warehouse_id || undefined,
          },
          showSearch: true,
          immediate: false,
          alwaysLoad: true,
          allowClear: true,
          mode: 'multiple',
          maxTagCount: 'responsive',
          visibleEvent: 'onFocus',
          onDropdownVisibleChange: (open: boolean) => {
            keyword.value.warehouse_id = ''
          },
        }
      },
      fieldName: 'goods_purchase_supply*id',
      label: '生产工厂',
      operator: 'IN',
    },
    // 新增：采购员
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchAdminOptions,
          filterOption: false,
          onSearch: useDebounceFn((value: string) => {
            keyword.value.admin_id = value
          }, 300),
          params: {
            keyword: keyword.value.admin_id || undefined,
          },
          showSearch: true,
          immediate: false,
          alwaysLoad: true,
          allowClear: true,
          mode: 'multiple',
          maxTagCount: 'responsive',
          visibleEvent: 'onFocus',
          onDropdownVisibleChange: (open: boolean) => {
            keyword.value.admin_id = ''
          },
        }
      },
      fieldName: 'a*buyer_id',
      label: '采购员',
      operator: 'IN',
    },
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchMerchandiserOptions,
          // filterOption: false,
          // onSearch: useDebounceFn((value: string) => {
          //   keyword.value.merchandiser = value
          // }, 300),
          // params: {
          //   keyword: keyword.value.merchandiser || undefined,
          // },
          showSearch: true,
          immediate: true,
          alwaysLoad: true,
          allowClear: true,
          mode: 'multiple',
          maxTagCount: 'responsive',
          // visibleEvent: 'onFocus',
          // onDropdownVisibleChange: (open: boolean) => {
          //   keyword.value.merchandiser = ''
          // },
        }
      },
      fieldName: 'goods*merchandiser',
      label: '跟单人',
      operator: 'IN',
    },
    // 新增：下单人
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchHeelManOptions,
          filterOption: false,
          onSearch: useDebounceFn((value: string) => {
            keyword.value.heel_man_name = value
          }, 300),
          params: {
            keyword: keyword.value.heel_man_name || undefined,
          },
          showSearch: true,
          immediate: false,
          alwaysLoad: true,
          allowClear: true,
          mode: 'multiple',
          maxTagCount: 'responsive',
          visibleEvent: 'onFocus',
          onDropdownVisibleChange: (open: boolean) => {
            keyword.value.heel_man_name = ''
          },
        }
      },
      fieldName: 'a*create_admin',
      label: '下单人',
      operator: 'IN',
    },
    {
      component: 'Select',
      fieldName: 'a*first_order',
      label: '性质',
      operator: '=',
      componentProps: {
        options: [
          { label: '首单', value: '1' },
          { label: '补单', value: '0' },
          { label: '加单', value: '2' },
          { label: '备料', value: '3' },
        ],
        allowClear: true,
        placeholder: '请选择性质',
      },
    },
    // 新增：物料类型
    {
      component: 'ApiSelect',
      componentProps: () => {
        return {
          api: fetchMaterialCategoryOptions,
          filterOption: false,
          onSearch: useDebounceFn((value: string) => {
            keyword.value.material_type = value
          }, 300),
          params: {
            keyword: keyword.value.material_type || undefined,
          },
          showSearch: true,
          immediate: false,
          alwaysLoad: true,
          allowClear: true,
          mode: 'multiple',
          maxTagCount: 'responsive',
          visibleEvent: 'onFocus',
          onDropdownVisibleChange: (open: boolean) => {
            keyword.value.material_type = ''
          },
        }
      },
      fieldName: 'd*material_type',
      label: '物料类型',
      operator: 'IN',
    },
    {
      component: 'Input',
      fieldName: 'd*material_name',
      label: '物料名称',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
        placeholder: '请输入物料名称',
      },
    },
    {
      component: 'Input',
      fieldName: 'e*sku_sn',
      label: '物料编号',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
        placeholder: '请输入物料编号',
      },
    },
    {
      component: 'Input',
      fieldName: 'a*purchase_name',
      label: '下单公司',
      operator: 'LIKE',
      componentProps: {
        allowClear: true,
        placeholder: '请输入下单公司',
      },
    },
    {
      component: 'RangePicker',
      fieldName: 'a*purchase_time',
      label: '下单日期',
      operator: 'RANGE',
      render: 'datestring',
      componentProps: {
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      component: 'RangePicker',
      fieldName: 'b*dead_line',
      label: '交货日期',
      operator: 'RANGE',
      render: 'datestring',
      componentProps: {
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      component: markRaw(TwoFields),
      disabledOnChangeListener: false,
      fieldName: 'b*expired_date',
      label: '逾期天数开始',
      operator: 'RANGE',
      valueToString: true,
      componentProps: {
        allowClear: true,
        placeholder: '逾期天数开始',
      },
    },
    {
      component: 'Select',
      fieldName: 'b*expired_status',
      label: '逾期状态',
      operator: 'IN',
      componentProps: {
        options: [
          { label: '未逾期', value: '1' },
          { label: '即将逾期', value: '2' },
          { label: '已逾期', value: '3' },
        ],
        allowClear: true,
        mode: 'multiple',
        maxTagCount: 'responsive',
        placeholder: '请选择逾期状态',
      },
    },
    {
      component: 'Select',
      fieldName: 'b*reviced_status',
      label: '收料状态',
      operator: 'IN',
      componentProps: {
        options: [
          { label: '未收料', value: '1' },
          { label: '部分收料', value: '2' },
          { label: '已完成收料', value: '3' },
        ],
        allowClear: true,
        mode: 'multiple',
        maxTagCount: 'responsive',
        placeholder: '请选择收料状态',
      },
    },
    {
      component: 'Select',
      fieldName: 'order_type',
      label: '排序方式',
      operator: '123',
      componentProps: {
        options: [
          { label: '预计上线日期-倒序', value: 'goods_purchase_progress.expected_launch_date desc' },
          { label: '预计上线日期-升序', value: 'goods_purchase_progress.expected_launch_date asc' },
          { label: '交货日期-倒序', value: 'b.dead_line desc' },
          { label: '交货日期-升序', value: 'b.dead_line asc' },
          { label: '逾期天数-倒序', value: 'b.expired_date desc' },
          { label: '逾期天数-升序', value: 'b.expired_date asc' },
          { label: '下单日期-倒序', value: 'a.purchase_time desc' },
          { label: '下单日期-升序', value: 'a.purchase_time asc' },
          { label: '供应商-倒序', value: 'c.SupplyNa desc' },
          { label: '供应商-升序', value: 'c.SupplyNa asc' },
          { label: '交期反馈-倒序', value: 'ee.delivery_feedback desc' },
          { label: '交期反馈-升序', value: 'ee.delivery_feedback asc' },
          { label: '发料数量-倒序', value: 'b.send_num desc' },
          { label: '发料数量-升序', value: 'b.send_num asc' },
        ],
        allowClear: true,
        placeholder: '请选择排序方式',
      },
    },
    {
      component: 'RangePicker',
      fieldName: 'goods_purchase_progress*expected_launch_date',
      label: '预计上线日期',
      operator: 'RANGE',
      render: 'datestring',
      componentProps: {
        valueFormat: 'YYYY-MM-DD',
      },
    },
    {
      component: 'Select',
      fieldName: 'a*is_bl',
      label: '是否大批量备料',
      operator: '=',
      componentProps: {
        options: [
          { label: '是', value: '1' },
          { label: '不是', value: '0' },
        ],
        allowClear: true,
        placeholder: '是否大批量备料',
      },
    },
    {
      component: 'Select',
      componentProps: {
        allowClear: true,
        options: [
          {
            label: '已上传',
            value: 1,
          },
          {
            label: '未上传',
            value: 0,
          },
        ],
        placeholder: '请选择',
      },
      fieldName: 'isUploadFile',
      label: '是否上传附件',
      operator: 'false',
    },
  ],
  showCollapseButton: true,
  collapsed: true,
  submitOnChange: false,
  submitOnEnter: true,
}

// 表格配置
const gridOptions: VxeTableGridOptions<RowType> = {
  border: true,
  showFooter: true,
  checkboxConfig: {
    highlight: true,
    reserve: true,
    showReserveStatus: true,
  },
  rowConfig: {
    useKey: true,
    keyField: 'id',
    //  isCurrent: true,
    isHover: true,
  },
  columnConfig: {
    useKey: true,
  },
  columns: [],
  height: 'auto',
  size: 'mini',
  keepSource: true,
  cellConfig: {
    height: 40,
  },
  rowStyle({ row, rowIndex }) {
    if (row.reviced_status !== undefined && [1, 2].includes(row.reviced_status) && row.expired_status == 3) {
    return { color: 'red' }
  }
  },
  pagerConfig: {
    pageSize: 30,
  },
  scrollX: {
    gt: 20,
  },
  editConfig: {
    mode: 'row',
    trigger: 'dblclick',
    showStatus: true,
  },
  menuConfig: {
    enabled: true,
    header: {},
    body: {
      options: [
        [
          {
            code: 'editRow',
            name: '修改',
            prefixIcon: 'vxe-icon-edit',
          },
          {
            code: 'doTag',
            name: '标记完成收料',
            prefixIcon: 'vxe-icon-edit',
          },
        ],
        [
          {
            code: 'copy',
            name: '复制',
            prefixIcon: 'vxe-icon-copy',
          },
          {
            code: 'copyRow',
            name: '复制行',
            prefixIcon: 'vxe-icon-copy',
          },
        ],
      ],
    },
  },
  proxyConfig: {
    autoLoad: false,
    ajax: {
      query: async ({ page }, formValues) => {
        const search = await gridApi.formApi.getFiltersValues(formValues)
        if (search.length === 0){
          message.error('请填写检索项')
          return
        }
        const sumData = await getPurchaseSum({
          page: page.currentPage,
          limit: page.pageSize,
          search,
        })
        var data = await getPurchaseIndex({
          page: page.currentPage,
          limit: page.pageSize,
          search,
        })
        columnsInit(data)
        // 将data.list的最后一个数组替换为sumData里的值，只替换存在的值
        if (data.list && data.list.length > 0 && sumData) {
          const lastIndex = data.list.length - 1
          const lastItem = data.list[lastIndex]

          // 遍历sumData的所有属性，只替换data.list最后一个数组中存在的属性
          Object.keys(sumData).forEach((key) => {
            if (lastItem.hasOwnProperty(key)) {
              lastItem[key] = sumData[key]
            }
          })
          footerData.value = lastItem
        }
        const displayList = data.list && data.list.length > 0 ? data.list.slice(0, -1) : data.list
        return {
          items: displayList,
          total: data.total,
        }
      },
    },
  },
  footerRowClassName: ({ row }) => {
    return 'text-red-500'
  },
  footerMethod: ({ columns, data }) => {
    return [footerData.value]
  },
  toolbarConfig: {
    custom: true,
    refresh: true,
    resizable: true,
    search: true,
    zoom: true,
  },
  id: 'material_purchase_progress_list',
  customConfig: {
    storage: true,
  },
}

// 初始化表格
const [Grid, gridApi] = useVbenVxeGrid({
  formOptions,
  gridOptions,
  gridEvents: {
    checkboxChange: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    },
    checkboxAll: () => {
      selectedRows.value = gridApi.grid.getCheckboxRecords()
    },
    cellDblclick: ({ row, column }) => {
      if (column.field === 'second_procurement_review') {
        AgainModalApi.setData({
          info: row,
          isEdit: false,
        }).open()
      }
    },
    menuClick: ({ menu, row, column }) => {
      switch (menu.code) {
        case 'editRow':
          if (row) {
            if (column.field === 'second_procurement_review') {
              // message.info(`复期: ${menu.name}`)
              AgainModalApi.setData({
                info: row,
                isEdit: true,
              }).open()
            } else {
              gridApi.grid.setEditRow(row)
            }
          }
          break
        case 'copy':
          if (row && column) {
            copyToClipboard(row[column.field])
          }
          break
        case 'copyRow':
          if (row) {
            const columns = gridApi.grid.getColumns()
            const header = columns.map((col: any) => ({
              label: col.title,
              value: col.field,
            }))
            copyToClipboard([row], header)
          }
          break
        case 'doTag':
          handleDoTag(row)
          // message.info(`点击了菜单123: ${row.id}`)
          break
        default:
          message.info(`点击了菜单: ${menu.name}`)
      }
    },
  },
})

const handleDoTag = (row: RowType) => {
  confirm({
    title: '标记完成',
    content: '确定要标记完成吗？',

  }).then(() => {
    signFinish({ purchase_bom_detail_id: row.purchase_bom_detail_id }).then(() => {
      message.success('标记完成成功')
      gridApi.query()
    })
  })
}

// 初始化表格列
const columnsInit = (res: any) => {
  header_data.value = res.all_header
  header_info.value = res.header_info
  field_data.value = res.all_field

  if (header_info.value && header_info.value.length > 0) {
    const dynamicColumns = header_info.value.map((col: any, index: number) => {
      const fieldConfig = field_data.value.find((f: any) => f.data === col.value) || {}
      let editRender = {}
      let cellRender = {}
      let slots = {}

      if (fieldConfig.is_write) {
        if (fieldConfig.type === 'date') {
          editRender = {
            name: 'CellDatePicker',
            props: { valueFormat: 'YYYY-MM-DD' },
          }
        } else if (fieldConfig.editor === 'select') {
          editRender = {
            name: 'CellSelect',
            options: fieldConfig.selectOptions.map((item: any) => ({ label: item, value: item })) || [],
          }
        } else {
          editRender = {
            name: 'CellInput',
          }
        }
      }
      if (col.value === 'template_images' || col.value === 'temp_imgs') {
        cellRender = {
          name: 'CellImage',
        }
      }else if(col.value === 'fp_detail'){
        slots= { default: 'fp_detail' }
      }
      return {
        field: col.value,
        title: col.label,
        width: fieldConfig.width || '80px',
        visible: !fieldConfig.className ? false : true,
        ...(fieldConfig.is_write && { editRender }),
        cellRender,
        slots
      }
    })

    gridApi.grid.loadColumn(dynamicColumns)
  }
}

/**
 * 获取 Tippy 弹层挂载目标
 * @returns 浏览器环境下返回 document.body，否则返回 undefined
 */
const getTippyAppendTarget = () => {
  return typeof document !== 'undefined' ? document.body : undefined
}

// 导出功能
const handleExport = async () => {
  const hide = message.loading('正在导出...', 0)
  try {
    const search = await gridApi.formApi.getFiltersValues()
    const apiFunction = dataType.value === '1' ? exportPurchaseProgress : exportPurchaseProgress2
    await apiFunction({
      search,
      is_exp: true,
    })
  } catch (e) {
    message.error('导出失败')
  } finally {
    hide()
  }
}

// 下载导出模版
const handleUrl = async () => {
  window.location.href = `${import.meta.env.VITE_GLOB_API_URL}/static/template/物料档案导入格式.xlsx`
}

// 保存编辑
const handleSave = async () => {
  if (gridApi) {
    const updateRecords = gridApi.grid.getUpdateRecords()
    // console.log(updateRecords)
    if (updateRecords.length > 0) {
      await savePurchaseProgress({ data: updateRecords })
        .then(() => {
          message.success('保存成功')
          gridApi.query()
        })
        .catch(() => {
          message.error('保存失败')
        })
    }
  }
}

// 数据类型切换
const handleDataTypeChange = (value: any) => {
  dataType.value = value.target.value
  gridApi.query()
}

// 弹窗组件
const [SendGoodsSkuModal, SendGoodsSkuModalApi] = useVbenModal({
  connectedComponent: SendGoodsSkuModalComponent,
})

// 操作：查看SKU详情
const handleViewSku = (row: RowType, type: string) => {
  SendGoodsSkuModalApi.setData({
    title: `采购单号:${row.goods_purchase_sn},货号:${row.goods_no}-已发货数量明细`,
    goods_purchase_sn: row.goods_purchase_sn,
    goods_id: row.goods_id,
  }).open()
}

const handleSearchTemplate = async () => {
  SearchTemplateModalApi.open()
}

// 弹窗组件
const [AgainModal, AgainModalApi] = useVbenModal({
  connectedComponent: Again,
})

// 弹窗组件
const [SearchTemplateModal, SearchTemplateModalApi] = useVbenModal({
  connectedComponent: SearchTemplate,
})

// 获取到期状态颜色
const getExpiredColor = (row: RowType) => {
  return row.is_expired === 1 ? 'error' : 'success'
}

// 获取完成状态颜色
const getCompletedColor = (row: RowType) => {
  return row.is_completed === 0 ? 'warning' : 'success'
}

// 获取超期天数颜色
const getDiffDayColor = (row: RowType) => {
  return row.diff_day > 0 ? 'error' : 'success'
}
// 获取字段配置
const getFieldConfig = (fieldName: string) => {
  return field_data.value.find((f: any) => f.data === fieldName) || {}
}

async function openPrompt() {
  prompt<string>({
    componentProps: {},
    title: '保存搜索条件',
    content: '自定义名称',
    // icon: 'question',
    overlayBlur: 3,
  })
    .then(async (res) => {
      // message.success(`用户输入了：${res}`)
      if (res) {
        const formValues = await gridApi.formApi.getValues()
        // 将对象转换为数组格式
        // const contentArray = Object.entries(formValues).map(([key, value]) => ({
        //   key,
        //   value,
        // }))
        saveSearchTemplate({
          title: res,
          data_type: dataType.value,
          group_name: 'MaterialPurchaseProgress',
          content: formValues,
        }).then(() => {
          message.success('保存成功')
        })
      }
    })
    .catch(() => {
      message.error('用户取消了输入')
    })
}

// 搜索条件选择框改变时，获取搜索条件内容
const changeWhere = async (value: any, content?: any) => {
  if (value && content) {
    // 将content中的key里的.替换为*
    const processedContent: any = {}
    Object.keys(content).forEach((key) => {
      const newKey = key.replace(/\./g, '*')
      processedContent[newKey] = content[key]
    })
    await gridApi.formApi.resetForm()
    await gridApi.formApi.setValues(processedContent)
  }
}
/**
 * 生成发料详情的提示内容
 * @param row 当前表格行数据
 * @returns 包含分配明细的提示 HTML 字符串
 */
const fpDetailTip = (row: RowType) => {
  const list = Array.isArray(row?.fp_list) ? [...row.fp_list] : []

  if (list.length === 0) {
    return '<div class="text-[9px]">暂无分配信息</div>'
  }

  const lastElement = list[list.length - 1]
  const detailList = list.slice(0, -1)

  const detailTip = detailList
    .map((item: any) => {
      return `分配简码：${item.template_no ?? '-'}  分配数量：${item.reviced_num ?? '-'}  未使用数量：${item.stock_num ?? '-'}  操作时间：${item.created_at ?? '-'}\n<br />`
    })
    .join('')

  const summaryTip = lastElement
    ? `总收料：${lastElement.reviced_num ?? '-'}  发料消耗：${lastElement.send_num ?? '-'}  拆分消耗：${lastElement.fp_num ?? '-'}  本单库存：${lastElement.stock_num ?? '-'}\n<br />`
    : ''

  return `<div class="text-[13px]">${detailTip}${summaryTip}</div>`
}

const fetchData = async () => {
  gridApi.reload()
}
</script>

<template>
  <Page auto-content-height>
    <Grid>
      <template #toolbar-actions>
        <!-- <Button type="ghost" class="mr-2 bg-[#cf892d] text-white hover:opacity-75" @click="handleUrl">下载导出模版</Button> -->
        <Button type="ghost" class="mr-2 bg-[#24b916] text-white hover:opacity-75" @click="handleExport">导出数据</Button>
        <Button type="ghost" class="mr-2 bg-[#006be6] text-white hover:opacity-75" @click="handleSave">保存编辑</Button>
        <!-- <Button type="ghost" class="mr-2 bg-[#16b9b1] text-white hover:opacity-75" @click="handleSearchTemplate">条件管理</Button>
        <Button type="ghost" class="mr-2 bg-[#3c72e6] text-white hover:opacity-75" @click="openPrompt">保存条件</Button>
        <div>
          <SearchTemplateSelect @change="changeWhere" />
        </div> -->
      </template>
      <template #toolbar-tools>
        <!-- <Radio.Group v-model:value="dataType" @change="handleDataTypeChange" class="ml-4">
          <Radio.Button value="1">实时取数</Radio.Button>
          <Radio.Button value="2">快照取数</Radio.Button>
        </Radio.Group> -->
      </template>

      <template #fp_detail="{ row }">
        <div
          v-tippy="{
            placement: 'top-end',
            maxWidth: '600px',
            allowHTML: true,
            interactive: true,
            hideOnClick: false,
            appendTo: getTippyAppendTarget,
            content: fpDetailTip(row),
          }"
        >
          {{ row.fp_detail }}
        </div>
      </template>

      <template #goodsNo="{ row }">
        <Button type="link" @click="handleViewSku(row, 'send')">{{ row.goods_no }}</Button>
      </template>

      <template #isExpiredText="{ row }">
        <Tag :color="getExpiredColor(row)">
          {{ row.is_expired_text }}
        </Tag>
      </template>

      <template #isCompletedText="{ row }">
        <Tag :color="getCompletedColor(row)">
          {{ row.is_completed_text }}
        </Tag>
      </template>

      <template #sendQuantity="{ row }">
        <Button type="link" @click="handleViewSku(row, 'send')">{{ row.send_quantity }}</Button>
      </template>

      <template #diffDay="{ row }">
        <span :style="{ color: getDiffDayColor(row) === 'error' ? 'red' : '' }">
          {{ row.diff_day }}
        </span>
      </template>

      <template #operation="{ row }">
        <!-- <Button class="mr-2" type="primary" size="small" @click="handleViewSku(row, 'send')">查看明细</Button> -->
      </template>
    </Grid>
    <SendGoodsSkuModal />
    <AgainModal @fetch-data="fetchData" />
    <SearchTemplateModal />
  </Page>
</template>
